package test.ground.springcache;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;
import java.util.Arrays;  

@Configuration  
@EnableCaching  
public class CacheConfig {  

    @Bean("customKeyGenerator")  
    public KeyGenerator customKeyGenerator() {  
        return (target, method, params) -> {  
            return target.getClass().getSimpleName() + "_" + method.getName() + "_" + Arrays.toString(params);  
        };  
    }  

    @Bean  
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {  
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()  
                .entryTtl(Duration.ofMinutes(10))  
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));  

        return RedisCacheManager.builder(connectionFactory)  
                .cacheDefaults(config)  
                .build();  
    }  
}